<template>
    <div id="container">
        <div id="writeCv">
            <!-- 基本信息模块 -->
            <div class="user-info-container" id="basicMessage">
                <el-card class="box-card">
                    <div slot="header" class="header-container">
                        <span class="title">基本信息</span>
                        <el-button v-if="!isBasicEditing" type="text" size="small" @click="startBasicEditing" class="edit-button">
                            <i class="el-icon-edit"></i> 编辑
                        </el-button>
                    </div>

                    <!-- 查看模式 -->
                    <div v-if="!isBasicEditing" class="view-mode">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <div label="姓名">
                                    {{ userInfo.name || '未设置' }}
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div label="出生日期">
                                    {{ formatBirthDate(userInfo.birthDate) || '未设置' }}
                                </div>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <div label="性别">
                                    {{ userInfo.gender || '未设置' }}
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div label="学历">
                                    {{ getEducationText(userInfo.education) || '未设置' }}
                                </div>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <div label="个人优势">
                                    {{ userInfo.personalAdvantages || '未设置' }}
                                </div>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <div label="期望企业">
                                    {{ userInfo.expectedIndustry || '未设置' }}
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div label="期望职业">
                                    {{ userInfo.expectedPosition || '未设置' }}
                                </div>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <div label="期望薪资">
                                    {{ userInfo.expectedSalary || '未设置' }}
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div label="位置">
                                    {{ userInfo.location || '未设置' }}
                                </div>
                            </el-col>
                        </el-row>
                    </div>

                    <!-- 编辑模式 -->
                    <el-form v-else ref="basicEditForm" :model="basicEditForm" label-width="100px" class="edit-mode">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="basicEditForm.name"></el-input>
                        </el-form-item>

                        <el-form-item label="出生日期" prop="birthDate">
                            <!-- 年份选择 -->
                            <el-select v-model="datePicker.year" placeholder="选择年份" @change="handleDateChange"
                                style="width: 100px; margin-right: 8px;">
                                <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
                            </el-select>

                            <!-- 月份选择 -->
                            <el-select v-model="datePicker.month" placeholder="选择月份" @change="handleDateChange"
                                style="width: 80px; margin-right: 8px;">
                                <el-option v-for="month in monthOptions" :key="month" :label="month" :value="month" />
                            </el-select>

                            <!-- 日期选择 -->
                            <el-select v-model="datePicker.day" placeholder="选择日期" @change="handleDateChange"
                                style="width: 80px;">
                                <el-option v-for="day in dayOptions" :key="day" :label="day" :value="day" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="性别" prop="gender">
                            <el-input v-model="basicEditForm.gender"></el-input>
                        </el-form-item>

                        <el-form-item label="学历" prop="education">
                            <el-select v-model="basicEditForm.education" placeholder="请选择学历">
                                <el-option v-for="(value, label) in educationOptions" :key="value" :label="label"
                                    :value="value"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="个人优势" prop="personalAdvantages">
                            <el-input v-model="basicEditForm.personalAdvantages"></el-input>
                        </el-form-item>

                        <el-form-item label="期望企业" prop="expectedIndustry">
                            <el-input v-model="basicEditForm.expectedIndustry"></el-input>
                        </el-form-item>

                        <el-form-item label="期望职业" prop="expectedPosition">
                            <el-input v-model="basicEditForm.expectedPosition"></el-input>
                        </el-form-item>

                        <el-form-item label="期望薪资" prop="expectedSalary">
                            <el-input v-model="basicEditForm.expectedSalary"></el-input>
                        </el-form-item>

                        <el-form-item label="位置" prop="location">
                            <LocationSelector ref="locationSelector" v-model="basicEditForm.location" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="saveBasicInfo" :loading="isSaving">
                                保存
                            </el-button>
                            <el-button @click="cancelBasicEditing">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <!-- 项目经验模块 -->
            <div class="user-info-container" id="projectExperience">
                <el-card class="box-card">
                    <div slot="header" class="header-container">
                        <span class="title">项目经验</span>

                        <el-button type="text" size="small" @click="openProjectDialog('add')" class="edit-button">
                            <i class="el-icon-plus"></i> 添加项目
                        </el-button>
                    </div>

                    <!-- 项目列表 -->
                    <div class="project-list">
                        <el-table :data="projectExperienceList
                            " stripe empty-text="暂无项目经验">
                            <el-table-column label="项目名称" prop="projectName"></el-table-column>
                            <el-table-column label="担任角色" prop="role"></el-table-column>
                            <el-table-column label="开始日期">
                                <template slot-scope="scope">
                                    {{ formatBirthDate(scope.row.createdAt) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="结束日期">
                                <template slot-scope="scope">
                                    {{ formatBirthDate(scope.row.endAt) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="180">
                                <template slot-scope="scope">
                                    <el-button type="text" size="mini"
                                        @click="openProjectDialog('edit', scope.$index, scope.row)" style="color: #41968d;">
                                        编辑
                                    </el-button>
                                    <el-button type="text" size="mini"
                                        @click="deleteProject(scope.$index, scope.row)" style="color: red;">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </div>

            <!-- 项目经验对话框 -->
            <el-dialog :visible.sync="projectDialogVisible" title="项目经验" width="60%"
                :before-close="handleProjectDialogClose">
                <el-form ref="projectForm" :model="projectForm" label-width="120px" :rules="projectRules">
                    <el-form-item label="项目名称" prop="projectName">
                        <el-input v-model="projectForm.projectName"></el-input>
                    </el-form-item>

                    <el-form-item label="项目描述" prop="projectDetail">
                        <el-input type="textarea" v-model="projectForm.projectDetail" rows="3"></el-input>
                    </el-form-item>

                    <el-form-item label="担任角色" prop="role">
                        <el-input v-model="projectForm.role"></el-input>
                    </el-form-item>

                    <el-form-item label="开始日期" prop="createdAt">
                        <el-date-picker v-model="projectForm.createdAt" type="date" placeholder="选择开始日期"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="结束日期" prop="endAt">
                        <el-date-picker v-model="projectForm.endAt" type="date" placeholder="选择结束日期" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-form>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="projectDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="saveProject">保存</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 工作经验模块 -->
            <div class="user-info-container" id="workExperience">
                <el-card class="box-card">
                    <div slot="header" class="header-container">

                        <span class="title">工作经验</span>

                        <el-button type="text" size="small" @click="openWorkDialog('add')" class="edit-button">
                            <i class="el-icon-plus"></i> 添加工作
                        </el-button>
                    </div>

                    <!-- 工作列表 -->
                    <div class="work-list">
                        <el-table :data="workExperienceList" stripe empty-text="暂无工作经验">
                            <el-table-column label="公司名称" prop="companyName"></el-table-column>
                            <el-table-column label="职位" prop="position"></el-table-column>
                            <el-table-column label="开始日期">
                                <template slot-scope="scope">
                                    {{ formatBirthDate(scope.row.createdAt) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="结束日期">
                                <template slot-scope="scope">
                                    {{ formatBirthDate(scope.row.endAt) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="180">
                                <template slot-scope="scope">
                                    <el-button type="text" size="mini"
                                        @click="openWorkDialog('edit', scope.$index, scope.row)" style="color: #41968d;">
                                        编辑
                                    </el-button>
                                    <el-button type="text" size="mini" @click="deleteWork(scope.$index, scope.row)" style="color: red;">

                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </div>

            <!-- 工作经验对话框 -->
            <el-dialog :visible.sync="workDialogVisible" title="工作经验" width="60%" :before-close="handleWorkDialogClose">
                <el-form ref="workForm" :model="workForm" label-width="120px" :rules="workRules">
                    <el-form-item label="公司名称" prop="companyName">
                        <el-input v-model="workForm.companyName"></el-input>
                    </el-form-item>

                    <el-form-item label="担任角色" prop="role">
                        <el-input v-model="workForm.role"></el-input>
                    </el-form-item>


                    <el-form-item label="开始日期" prop="createdAt">
                        <el-date-picker v-model="workForm.createdAt" type="date" placeholder="选择开始日期"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="结束日期" prop="endAt">
                        <el-date-picker v-model="workForm.endAt" type="date" placeholder="选择结束日期" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="工作内容" prop="workContent">
                        <el-input type="textarea" v-model="workForm.workContent" rows="3"></el-input>
                    </el-form-item>
                </el-form>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="workDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="saveWork">保存</el-button>
                    </span>
                </template>
            </el-dialog>

        </div>
    </div>
</template>

<script>
// 在组件顶部添加引入
import debounce from 'lodash/debounce';
import { mapState } from 'vuex';
import LocationSelector from '@/components/localSelect.vue'
export default {
    name: 'PersonCv',
    components: {
        LocationSelector
    },

    data() {
        return {
            // 基本信息编辑状态
            basicEditForm: {},
            isBasicEditing: false,
            isSaving: false,
            // 日期选择器状态
            datePicker: {
                year: '',   // 选中的年份
                month: '',  // 选中的月份（01-12）
                day: ''     // 选中的日期（01-31）
            },
            // 年份选项（可动态生成，这里示例近 100 年）
            yearOptions: [],
            // 月份选项（固定 01-12）
            monthOptions: Array.from({ length: 12 }, (_, i) => (i + 1).toString().padStart(2, '0')),
            // 日期选项（动态生成）
            dayOptions: [],
            educationOptions: {
                '其他': 'OTHER',
                '硕士': 'MASTER',
                '本科': 'UNDERGRADUATE',
                '专科': 'COLLEGE',
                '博士': 'DOCTOR'
            },
            educationMap: {
                OTHER: '其他',
                MASTER: '硕士',
                UNDERGRADUATE: '本科',
                COLLEGE: '专科',
                DOCTOR: '博士'
            },

            // 项目经验
            projectDialogVisible: false,
            projectDialogType: 'add', // 'add' 或 'edit'
            projectIndex: -1,
            projectForm: {},
            projectRules: {
                // projectName: [
                //     { required: true, message: '请输入项目名称', trigger: 'blur' }
                // ],
                // role: [
                //     { required: true, message: '请输入担任角色', trigger: 'blur' }
                // ],
                // createdAt: [
                //     { required: true, message: '请选择开始日期', trigger: 'change' }
                // ]
            },
            insertString: 'T11:27:27.252Z',

            // 工作经验
            workDialogVisible: false,
            workDialogType: 'add', // 'add' 或 'edit'
            workIndex: -1,
            workForm: {},
            workRules: {
                companyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' }
                ],
                position: [
                    { required: true, message: '请输入职位', trigger: 'blur' }
                ],
                createdAt: [
                    { required: true, message: '请选择开始日期', trigger: 'change' }
                ]
            },

            // 防抖保存函数
            debouncedSaveBasicInfo: null
        }
    },
    methods: {
        // 开始编辑基本信息
        startBasicEditing() {
            this.isBasicEditing = true;
            this.resetBasicForm();
        },

        // 取消编辑基本信息
        cancelBasicEditing() {
            this.isBasicEditing = false;
            this.resetBasicForm();
        },

        // 重置基本信息表单
        resetBasicForm() {
            // 深拷贝userInfo到editForm
            const initData = this.userInfo || {};
            this.basicEditForm = JSON.parse(JSON.stringify(initData));

            // 解析 birthDate 并拆分到 datePicker
            if (initData.birthDate) {
                const [datePart] = initData.birthDate.split('T')[0].split('-');
                const [year, month, day] = datePart.split('-');
                this.datePicker = { year, month, day };
                // 手动触发日期联动（生成天数选项）
                this.handleDateChange();
            } else {
                this.datePicker = { year: '', month: '', day: '' };
                this.dayOptions = [];
            }

            this.originalBasicInfo = JSON.parse(JSON.stringify(this.userInfo));
        },

        // 保存基本信息（手动提交）
        saveBasicInfo() {
            if (!this.hasBasicChanges) return;
            this.$refs.basicEditForm.validate(valid => {
                if (valid) {
                    this.isSaving = true;
                    this.saveBasicInfoToBackend()
                        .then(() => {
                            this.isBasicEditing = false;
                            this.$message.success('保存成功');
                        })
                        .finally(() => {
                            this.isSaving = false;
                        });
                } else {
                    this.$message.error('请检查表单信息');
                    return false;
                }
            });
        },

        // 保存基本信息到后端（自动/手动）
        async saveBasicInfoToBackend() {
            if (!this.hasBasicChanges) return;

            try {
                // 发送变更到后端
                const response = await this.$store.dispatch('seeker/updateUserInfo', this.basicEditForm);

                // 更新原始表单数据
                this.originalBasicInfo = JSON.parse(JSON.stringify(this.basicEditForm));

                return response;
            } catch (error) {
                this.$message.error(`保存失败: ${error.message}`);
                console.error('更新基本信息失败:', error);

                // 发生错误时回滚到原始数据
                this.basicEditForm = JSON.parse(JSON.stringify(this.originalBasicInfo));

                throw error;
            }
        },

        // 处理日期选择变化
        handleDateChange() {
            const { year, month } = this.datePicker;
            if (!year || !month) return;

            // 计算当月天数（考虑闰年）
            const daysInMonth = new Date(year, month, 0).getDate();
            this.dayOptions = Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString().padStart(2, '0'));

            // 拼接日期并更新表单
            this.updateBirthDate();
        },

        // 更新表单中的 birthDate
        updateBirthDate() {
            const { year, month, day } = this.datePicker;
            if (year && month && day) {
                // 拼接为 YYYY-MM-DD 格式
                const datePart = `${year}-${month}-${day}`;
                // 追加固定时间部分
                this.basicEditForm.birthDate = `${datePart}T07:15:31.545Z`;
            } else {
                this.basicEditForm.birthDate = '';
            }
        },

        //拆分日期
        formatBirthDate(birthDate) {
            if (!birthDate) return '';
            // 拆分出日期部分（去掉 T 后面的时间）
            return birthDate.split('T')[0];
        },

        //学历枚举值映射
        getEducationText(enumValue) {
            return this.educationMap[enumValue] || enumValue;
            // 若没找到映射，默认返回原始值（可选逻辑，根据需求调整）
        },

        // 打开项目经验对话框
        openProjectDialog(type, index = -1, row = {}) {
            this.projectDialogType = type;
            this.projectIndex = index;

            if (type === 'edit') {
                // 编辑模式，填充表单
                this.projectForm = JSON.parse(JSON.stringify(row));
            } else {
                // 添加模式，清空表单
                this.projectForm = {
                    id: -1,
                    projectName: '',
                    projectDetail: '',
                    role: '',
                    createdAt: '',
                    endAt: '',
                };
            }

            this.projectDialogVisible = true;
        },

        // 关闭项目经验对话框
        handleProjectDialogClose(done) {
            if (this.hasProjectChanges) {
                this.$confirm('确认关闭吗？您的修改将不会保存。', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    done();
                }).catch(() => {
                    // 取消关闭
                });
            } else {
                done();
            }
        },

        // 保存项目经验
        async saveProject() {
            try {
                // 验证表单
                await new Promise((resolve, reject) => {
                    this.$refs.projectForm.validate(valid => {
                        if (valid) {
                            resolve();
                        } else {
                            this.$message.error('请检查表单信息');
                        }
                    });
                });

                // 确保使用组件中的projectExperienceList数据
                const projectExperienceList = [...this.projectExperienceList];

                if (this.projectDialogType === 'add') {
                    // 添加新项目
                    if (this.projectForm.createdAt) {
                        this.projectForm.createdAt = `${this.projectForm.createdAt}${this.insertString}`;
                    };
                    if (this.projectForm.endAt) {
                        this.projectForm.endAt = `${this.projectForm.endAt}${this.insertString}`;
                    };
                    projectExperienceList.push(this.projectForm);
                    this.$message.success('项目经验添加成功');
                } else {
                    // 编辑现有项目
                    projectExperienceList[this.projectIndex] = this.projectForm;
                    this.$message.success('项目经验更新成功');
                }

                // 通过Vuex更新状态
                await this.$store.dispatch('seeker/renewProjectExperience', {

                    projectExperience: projectExperienceList
                });

                this.projectDialogVisible = false;

            } catch (error) {
                console.error('保存项目经验过程中出错:', error);
                this.$message.error('保存项目经验失败: ' + error.message);
            }
        },

        // 删除项目经验
        deleteProject(index, row) {
            this.$confirm(`确认删除项目 "${row.projectName}" 吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const projectExperienceList = this.projectExperienceList
                    projectExperienceList.splice(index, 1);

                    // 更新到Vuex和后端
                    await this.$store.dispatch('seeker/renewProjectExperience', {
                        projectExperience: projectExperienceList
                    });

                    this.$message.success('项目经验已删除');
                } catch (error) {
                    this.$message.error('删除项目经验失败: ' + error.message);
                }
            }).catch(() => {
                // 取消操作
            });
        },

        // 打开工作经验对话框
        openWorkDialog(type, index = -1, row = {}) {
            this.workDialogType = type;
            this.workIndex = index;

            if (type === 'edit') {
                // 编辑模式，填充表单
                this.workForm = JSON.parse(JSON.stringify(row));
            } else {
                // 添加模式，清空表单
                this.workForm = {
                    id: -1,
                    companyName: '',
                    role: '',
                    createdAt: '',
                    endAt: '',
                    workContent: '',
                };
            }

            this.workDialogVisible = true;
        },

        // 关闭工作经验对话框
        handleWorkDialogClose(done) {
            if (this.hasWorkChanges) {
                this.$confirm('确认关闭吗？您的修改将不会保存。', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    done();
                }).catch(() => {
                    // 取消关闭
                });
            } else {
                done();
            }
        },

        // 保存工作经验
        async saveWork() {
            this.$refs.workForm.validate(valid => {
                if (valid) {
                    try {
                        const workExperienceList = [...this.workExperienceList];

                        if (this.workDialogType === 'add') {
                            if (this.workForm.createdAt) {
                                this.workForm.createdAt = `${this.workForm.createdAt}${this.insertString}`;
                            };
                            if (this.workForm.endAt) {
                                this.workForm.endAt = `${this.workForm.endAt}${this.insertString}`;
                            };
                            // 添加新工作
                            workExperienceList.push(this.workForm);

                            this.$message.success('工作经验添加成功');
                        } else {
                            // 编辑现有工作
                            workExperienceList[this.workIndex] = this.workForm;

                            this.$message.success('工作经验更新成功');
                        }

                        // 更新到Vuex和后端
                        this.$store.dispatch('seeker/renewWorkExperience', {
                            workExperience: workExperienceList
                        });

                        this.workDialogVisible = false;
                    } catch (error) {
                        this.$message.error('保存工作经验失败: ' + error.message);
                    }
                } else {
                    this.$message.error('请检查表单信息');
                    return false;
                }
            });
        },

        // 删除工作经验
        deleteWork(index, row) {
            this.$confirm(`确认删除工作 "${row.companyName}" 吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const workExperienceList = this.workExperienceList;
                    workExperienceList.splice(index, 1);

                    // 更新到Vuex和后端
                    await this.$store.dispatch('user/updateUserInfo', {
                        workExperience: workExperienceList
                    });

                    this.$message.success('工作经验已删除');
                } catch (error) {
                    this.$message.error('删除工作经验失败: ' + error.message);
                }
            }).catch(() => {
                // 取消操作
            });
        },
    },
    computed: {
        ...mapState('seeker', {
            // 映射 userInfo 状态
            userInfo: state => state.userInfo,
            // 映射 projectExperience 状态，并确保初始化为数组
            projectExperienceList: state => state.projectExperience || [],
            // 映射 workExperience 状态，并确保初始化为数组
            workExperienceList: state => state.workExperience || [],
        }),
        hasBasicChanges() {
            // 对比编辑表单和原始数据是否有差异
            return JSON.stringify(this.basicEditForm) !== JSON.stringify(this.originalBasicInfo);
        }
    },
    watch: {
        // 监听Vuex中userInfo的变化（外部更新）
        userInfo: {
            handler(newVal) {
                if (!this.isBasicEditing) {
                    this.resetBasicForm();
                }
            },
            deep: true
        },
        projectExperience: {
            handler(newVal) {
                this.projectExperienceList = newVal;
            },
            deep: true
        },
        workExperience: {
            handler(newVal) {
                this.workExperience = newVal;
            },
            deep: true
        }

    },
    created() {
        // 初始化防抖函数
        this.debouncedSaveBasicInfo = debounce(this.saveBasicInfoToBackend, 1000);
        // 生成年份列表
        const currentYear = new Date().getFullYear();
        this.yearOptions = Array.from({ length: 100 }, (_, i) => (currentYear - i).toString());
    },
}
</script>

<style scoped>
#writeCv{
    background: none;
}


#container {
    background: none;
}

.user-info-container {
    margin: 20px auto;
    width: 80%;
}

#contents {
    width: 100px;
    height: 100%;
    background-color: rgb(239, 239, 237);
}

.header-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    padding: 15px 0;

}

.edit-button{
    right: 320px;
    position: absolute;
    color: #41968d;

}

.edit-button:hover{
    color: #026e62;
}


.title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
</style>